package com.daisuxia.payRoute;

import org.springframework.beans.factory.annotation.Autowired;

import com.daisuxia.baofoo.BaofooCutPayUtil;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.risk.service.OutOrdersService;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.util.GenerateNo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Created by dhl on 2017/5/18.
 */

public class BaofooPay implements IPayCommons {


	private IPayCommons nextIPayCommons;


	private IOutOrdersService outOrdersService;

	public BaofooPay(IOutOrdersService outOrdersService){
		this.outOrdersService = outOrdersService;
	}


	@Override
	public void setNextSuccessor(IPayCommons iPayCommons) {
		this.nextIPayCommons = iPayCommons;
	}

	@Override
	public Map handleOrder(Map map) throws IOException, URISyntaxException {

		try {
			Repayment re = (Repayment)map.get("repayment");
			User user = (User)map.get("user");
			UserCardInfo userCardInfo = (UserCardInfo)map.get("userCardInfo");
			String orderNo = GenerateNo.payRecordNo(user.getId());
			Map result = BaofooCutPayUtil.cutApi(
					userCardInfo.getCard_no(),
					user.getIdNumber(),
					user.getRealname(),
					userCardInfo.getPhone(),
					orderNo,
					(re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00 + ""
			);
			String ourOrders = result.get("payCutType").toString();//支付机构
			String signParam = result.get("qbm_signParam").toString();//请求参数
			OutOrders outOrders = new OutOrders();
			outOrders.setUserId(user.getId());
			outOrders.setAssetOrderId(re.getId());
			outOrders.setOrderType(ourOrders);
			outOrders.setOrderNo(orderNo);
			outOrders.setAct(OutOrders.ACT_DEBIT);
			outOrders.setReqParams(signParam);
			outOrders.setReturnParams(result.toString());

			outOrdersService.insert(outOrders);
			if ("0000".equals(result.get("resp_code").toString())) {
				result.put("payCutType", OutOrders.TYPE_BAOFOO);//代扣类型
				return result;
			}else if(BaofooCutPayUtil.errorCodes.contains(result.get("resp_code").toString())){
				//先查询一次
				Map queryMap = BaofooCutPayUtil.simpleTransApi(orderNo,result.get("trade_date").toString());

				//处理中返回 获取处理成功 那就返回
				if("I".equals(queryMap.get("order_stat").toString())){

					return result;
				}else if("S".equals(queryMap.get("order_stat").toString())){
					result.put("resp_code","0000");
					//修改订单的返回码
					outOrders.setReturnParams(result.toString());
					outOrdersService.updateByOrderNo(outOrders);
					return result;
				}
			}else if(nextIPayCommons == null){
				return result;
			}else{
				outOrders.setStatus(OutOrders.STATUS_OTHER);
				outOrdersService.updateByOrderNo(outOrders);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return nextIPayCommons.handleOrder(map);
	}
}
